<template>
  <div>
    <a-form :model="queryParams" ref="queryForm" :inline="true" label-width="auto">
      <a-form-item label="用户名称" prop="userName">
        <a-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </a-form-item>
      <a-form-item label="用户昵称" prop="nickName">
        <a-input v-model="queryParams.nickName" placeholder="请输入用户昵称" clearable size="small" @keyup.enter.native="handleQuery" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" icon="a-icon-search" size="mini" @click="handleQuery">搜索</a-button>
        <a-button type="default" icon="a-icon-refresh" size="mini" @click="resetQuery">重置</a-button>
        <a-button type="primary" plain icon="a-icon-plus" size="mini" @click="formAdd">添加</a-button>
      </a-form-item>
    </a-form>
    <a-table v-loading="loading" :border="true" :data="dataList">
      <a-table-column label="组织名称" align="center" key="deptName" prop="dept.deptName" :show-overflow-tooltip="true" />
      <a-table-column label="用户名称" align="center" key="userName" prop="userName" :show-overflow-tooltip="true" />
      <a-table-column label="用户昵称" align="center" key="nickName" prop="nickName" :show-overflow-tooltip="true" />
      <a-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120" />
      <a-table-column label="状态" align="center" key="status">
        <template slot-scope="scope">
          <a-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></a-switch>
        </template>
      </a-table-column>
      <a-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </a-table-column>
      <a-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <a-button size="mini" type="text" icon="a-icon-edit" @click="formUpdate(scope.row)" v-hasPermi="['system:user:edit']">修改</a-button>
          <a-button v-if="scope.row.userId !== 1" size="mini" type="text" icon="a-icon-delete" @click="formDelete(scope.row)"
            v-hasPermi="['system:user:remove']">删除</a-button>
          <a-button size="mini" type="text" icon="a-icon-key" @click="formResetPwd(scope.row)" v-hasPermi="['system:user:resetPwd']">重置
          </a-button>
        </template>
      </a-table-column>
    </a-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    <br />

    <!-- 添加或修改对话框 -->
    <a-modal :title="formTitle" :visible.sync="formOpen" width="600px" append-to-body>
      <a-form ref="form" :model="form" :rules="formRules" label-width="80px">
        <a-row>
          <a-col :span="12">
            <a-form-item label="归属组织" prop="deptId">
              <VueTreeSelect v-model="form.deptId" :options="unitList" :normalizer="unitFormat" :default-expand-level="3" placeholder="请选择归属组织" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="用户昵称" prop="nickName">
              <a-input v-model="form.nickName" placeholder="请输入用户昵称" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item v-if="form.userId == undefined" label="用户名称" prop="userName">
              <a-input v-model="form.userName" placeholder="请输入用户名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item v-if="form.userId == undefined" label="用户密码" prop="password">
              <a-input v-model="form.password" placeholder="请输入用户密码" type="password" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="手机号码" prop="phonenumber">
              <a-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="邮箱" prop="email">
              <a-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="用户性别">
              <a-select v-model="form.sex" placeholder="请选择">
                <a-option v-for="dict in sexOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态">
              <a-radio-group v-model="form.status">
                <a-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictValue">{{dict.dictLabel}}
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="岗位">
              <a-select v-model="form.postIds" multiple placeholder="请选择">
                <a-option v-for="item in postOptions" :key="item.postId" :label="item.postName" :value="item.postId" :disabled="item.status == 1">
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="角色">
              <a-select v-model="form.roleIds" multiple placeholder="请选择">
                <a-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId" :disabled="item.status == 1">
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-item label="备注">
              <a-input v-model="form.remark" type="textarea" placeholder="请输入内容"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div slot="footer" class="dialog-footer">
        <a-button type="primary" @click="formSubmit">确 定</a-button>
        <a-button @click="formCancel">取 消</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
  import {
    listDept,
    getDept,
    delDept,
    addDept,
    updateDept
  } from "@/api/system/dept";
  import {
    listUser,
    getUser,
    delUser,
    addUser,
    updateUser,
    resetUserPwd,
    changeUserStatus
  } from "@/api/system/user";

  import VueTreeSelect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

  export default {
    name: "UserTable",
    components: {
      VueTreeSelect
    },
    props: {
      ancestors: {
        type: Number,
        default: 0
      },
      roleKey: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        loading: true,
        dataList: [],
        unitList: [],
        total: 0,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          unitId: null
        },
        form: {},
        formTitle: "",
        formOpen: false,
        // 默认密码
        initPassword: undefined,
        // 状态数据字典
        statusOptions: [],
        // 性别状态字典
        sexOptions: [],
        // 岗位选项
        postOptions: [],
        // 角色选项
        roleOptions: [],
        // 表单校验
        formRules: {
          deptId: [{
            required: true,
            message: "组织名称不能为空",
            trigger: "blur"
          }],
          userName: [{
            required: true,
            message: "用户名称不能为空",
            trigger: "blur"
          }],
          nickName: [{
            required: true,
            message: "用户昵称不能为空",
            trigger: "blur"
          }],
          password: [{
            required: true,
            message: "用户密码不能为空",
            trigger: "blur"
          }],
          email: [{
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }],
          phonenumber: [{
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }]
        }
      };
    },
    created() {
      this.getUnitList();
      this.getList();

      this.getDicts("sys_normal_disable").then(response => {
        this.statusOptions = response.data;
      });
      this.getDicts("sys_user_sex").then(response => {
        this.sexOptions = response.data;
      });
      this.getConfigKey("sys.user.initPassword").then(response => {
        this.initPassword = response.msg;
      });
    },
    methods: {
      /** 查询组织列表 */
      getUnitList() {
        this.loading = true;
        listDept({
          ancestors: this.ancestors
        }).then(response => {
          this.unitList = this.handleTree(response.data, "deptId");
          this.loading = false;
        });
      },
      /** 转换组织数据结构 */
      unitFormat(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        };
        return {
          id: node.deptId,
          label: node.deptName,
          children: node.children
        };
      },
      // 节点单击事件
      unitNodeClick(data, col) {
        if (col.label !== '操作') {
          this.queryParams.deptId = data.deptId;
          this.getList();
        }
      },
      /** 查询列表 */
      getList() {
        this.loading = true;
        if (!this.queryParams.deptId || this.queryParams.deptId == '') {
          this.queryParams.deptId = this.ancestors;
        }
        listUser(this.queryParams).then(response => {
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      formReset() {
        this.form = {};
        this.resetForm("form");
      },
      formCancel() {
        this.formOpen = false;
        this.formReset();
      },
      formAdd() {
        this.formReset();
        getUser().then(response => {
          this.postOptions = response.posts;
          this.roleOptions = [];
          for (let idx in response.roles) {
            let item = response.roles[idx];
            if (item.roleKey.indexOf(this.roleKey) > -1) {
              this.roleOptions.push(item);
            }
          }
          this.formOpen = true;
          this.formTitle = "添加用户";
          this.form.password = this.initPassword;
        });
      },
      formUpdate(row) {
        this.formReset();
        const userId = row.userId;
        getUser(userId).then(response => {
          this.form = response.data;
          this.postOptions = response.posts;
          this.roleOptions = [];
          for (let idx in response.roles) {
            let item = response.roles[idx];
            if (item.roleKey.indexOf(this.roleKey) > -1) {
              this.roleOptions.push(item);
            }
          }
          this.form.postIds = response.postIds;
          this.form.roleIds = response.roleIds;
          this.formOpen = true;
          this.formTitle = "修改用户";
          this.form.password = "";
        });
      },
      /** 提交按钮 */
      formSubmit() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.userId != null) {
              updateUser(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.formOpen = false;
                this.getList();
              });
            } else {
              addUser(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.formOpen = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      formDelete(row) {
        let id = row.userId;
        this.$confirm('是否确认删除编号为"' + id + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delUser(id);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
      },
      /** 重置密码按钮操作 */
      formResetPwd(row) {
        this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }).then(({
          value
        }) => {
          resetUserPwd(row.userId, value).then(response => {
            this.msgSuccess("修改成功，新密码是：" + value);
          });
        }).catch(() => {});
      },
    }
  };
</script>
